package com.zyx.maildemo.service;
import	java.util.Objects;

import com.zyx.maildemo.entity.RoleEnum;
import com.zyx.maildemo.entity.Roles;
import com.zyx.maildemo.entity.User;
import com.zyx.maildemo.entity.UserRole;
import com.zyx.maildemo.entity.example.UserExample;
import com.zyx.maildemo.exception.ServiceException;
import com.zyx.maildemo.mapper.UserMapper;
import com.zyx.maildemo.mapper.UserRoleMapper;
import com.zyx.maildemo.utils.NumberUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName: UserServiceImpl
 * @author: zyx
 * @E-mail: 1377631190@qq.com
 * @DATE: 2019/7/27 13:14
 */
@Slf4j
@Service
public class UserService {

    private UserMapper userMapper;
    private UserRoleService userRoleService;
    private RolesService rolesService;

    public UserService() {
    }

    @Autowired
    public UserService(UserMapper userMapper,
                       UserRoleService userRoleService,
                       RolesService rolesService) {
        this.userMapper = userMapper;
        this.userRoleService = userRoleService;
        this.rolesService = rolesService;
    }

    @Transactional
    public boolean register(User user) {
        String hashPwd = hashPwd(user);
        int i = 0;
        if (!StringUtils.isEmpty(hashPwd)) {
            user.setDatetime(new Date());
            user.setPassword(hashPwd);
            // 添加默认的用户角色
            if (CollectionUtils.isEmpty(user.getRoles())) {
                Roles one = rolesService.findOne(RoleEnum.USER.toString().toLowerCase());
                user.getRoles().add(one);
            }

            i = userMapper.insertSelective(user);
            setUserRole(user);
        }
        return i > 0;
    }

    protected void setUserRole(User user) {
        if (NumberUtils.isZero(user.getId()) || CollectionUtils.isEmpty(user.getRoles()))
            throw new ServiceException("用户注册失败,无法保存角色!");
        List<UserRole> userRoles = user.getRoles().stream()
                .filter(Objects::nonNull)
                .map(roles -> {
                    UserRole userRole = new UserRole();
                    userRole.setUserId(user.getId());
                    userRole.setRoleId(roles.getId());
                    return userRole;
                }).collect(Collectors.toList());
        userRoleService.addBatch(userRoles);
    }

    public boolean login(User user) {
        if (user != null) {
            UserExample userExample = new UserExample();
            UserExample.Criteria criteria = userExample.createCriteria();
            criteria.andUsernameEqualTo(user.getUsername());
            List<User> users = userMapper.selectByExample(userExample);
            String pwd = hashPwd(user);
            if (CollectionUtils.isEmpty(users))
                throw new RuntimeException("用户名或密码错误");
            if (!pwd.equals(users.get(0).getPassword()))
                throw new RuntimeException("用户名或密码错误");
            user.setPassword(pwd);
            return true;
        }
        return false;
    }

    /**
     * 对用户进行md5加密
     */
    private String hashPwd(User user) {
        try {
            Md5Hash hash = new Md5Hash(user.getPassword(), user.getUsername(), 21);
            return hash.toHex();
        } catch (Exception e) {
            log.error("Hash加密失败! name: {}, passwrod: {}", user.getUsername(), user.getPassword());;
            return "";
        }
    }

    public User findByName(String username) {
        return userMapper.selectByName(username);
    }

}
